<?php

namespace Yolo\Components\Validator;

use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\MessageBag;
use Hyperf\Validation\ValidatorFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class Validator implements ValidatorInterface
{
    /**
     * Validate the given data against the provided rules.
     * @param array $rules the rules to validate against
     * @param array $data the data to validate
     * @param array $messages the custom error messages
     * @param array $attributes the custom attributes to validate
     * @return MessageBag|null
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function validate(array $rules, array $data, array $messages = [], array $attributes = []): ?MessageBag
    {
        $validator = ApplicationContext::getContainer()->get(ValidatorFactory::class)->make(
            $data,
            $rules,
            $messages,
            $attributes
        );

        if ($validator->fails()) {
            return $validator->errors();
        }

        return null;
    }
}
